package currentment.count;

import java.util.concurrent.CountDownLatch;

public class LockCount {
    private static volatile int count = 0; // 共享的volatile计数器
    private static final int TARGET = 1000; // 目标值
    private static final CountDownLatch latch = new CountDownLatch(1); // 用于主线程等待

    public static void main(String[] args) {
        Thread[] threads = new Thread[50];

        for (int i = 0; i < 50; i++) {
            threads[i] = new Thread(() -> {
                while (true) {
                    synchronized (LockCount.class) {
                        if (count >= TARGET) {
                            latch.countDown();
                            break;
                        }
                        count++;
                    }
                }
            });
            threads[i].start();
        }

        try {
            latch.await();
            System.out.println("Count reached 1000!");
        } catch (InterruptedException ignored) {

        }

        // 等待所有线程完成
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }

        System.out.println("Final count: " + count);
    }
}
